package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.ResUtils;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.service.RedisService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivityCard;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.activity.ActivityCardJpa;
import cn.hiapi.shopkeeper.request.CreateOrderRequest;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2023/1/1 22:29
 */
@Service
public class ActivityCardService extends AbsActivityService<ActivityCardJpa, ActivityCard, Long> {
    public ActivityCardService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }

    @Override
    public ActivityType getActivityType() {
        return ActivityType.CARD;
    }

    @Override
    @Transactional
    public BasicEntity saveExpand(long aid, JSONObject data) {
        ActivityCard card = data.toJavaObject(ActivityCard.class);
        if (card == null) throw new BasicException("次卡数据错误");

        if (StringUtils.isEmpty(card.getTitle())) {
            throw new BasicException("次卡标题错误");
        }
        if (StringUtils.isEmpty(card.getColor())) {
            throw new BasicException("颜色错误");
        }
        if (card.getNumber() <= 0) throw new BasicException("次数错误");
        if (card.getPrice() == null || card.getPrice().compareTo(BigDecimal.ZERO) <= 0)
            throw new BasicException("售卖价格错误");
        if (card.getStockNum() <= 0) throw new BasicException("库存数量错误");
        card.setAid(aid);
        return this.save(card);
    }

    @Override
    @Transactional
    public int deleteByAid(long aid) {
        return ResUtils.getDefault(this.repository.deleteByAid(aid));
    }

    @Override@Transactional
    public ActivityOrder createOrder(BasicEntity basic, Activity activity, Map<String, Long> incrementStock, CreateOrderRequest request, Token<Object> token) {
        ActivityCard card = (ActivityCard) basic;
        if (card == null) throw new BasicException("次卡活动不存在");
        if (card.getLimitNum() > 0) {
            long count = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(
                    new QueryWrapper().eq("aid", activity.getId())
                            .eq("buyerId",token.getFid())
                            .eq("statusType", 1).eq("activityType", activity.getType())
            );
            if (count >= card.getLimitNum())
                throw new BasicException("超过限购数量");
        }
        final long stockNum = card.getStockNum();
        long total = this.dispatchContext.getServiceOne(ProductNumService.class).totalByGid(activity.getId(), AppConst.ACTIVITY_SELL_TOTAL);
        long increment = this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 0L);
        if ((total + increment) >= stockNum) {
            throw new BasicException("次卡已售罄");
        }
        this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 1L);
        incrementStock.put(AppConst.ACTIVITY_STOCK_LOCK, activity.getId());
        ActivityOrder order = new ActivityOrder();
        if (request.getSugar() != null)
            order.setSugar(request.getSugar());
        order.setPrice(card.getPrice());
        order.setCostPrice(activity.getPrice());

        return order;
    }

    @Override
    public BigDecimal sugarDeduction(Activity activity, BigDecimal rate, BigDecimal amount, long uid) {
        ActivityCard card = super.getByAid(activity.getId());
        return super.sugarDeduction(card.getPrice(),rate,amount);
    }
}
